<template>
  <div v-loading="loading">
    <my-upload
      v-model="show"
      :width="300"
      :height="300"
      :no-circle="true"
      field="img"
      img-format="png"
      @src-file-set="getFile"
      @crop-success="cropSuccess"
      @crop-upload-fail="cropUploadFail"/>
    <div class="clickUpload" @click="toggleShow">
      <img v-if="imgDataUrl" :src="imgDataUrl" alt="" class="imgDataUrl">
      <i v-else class="el-icon-plus avatar-uploader-icon"/>
    </div>
  </div>
</template>
<style lang="scss">
  .clickUpload {
    text-align: center;
    width: 70px;
    height: 70px;
    border: 1px dashed #dcdcdc;
    line-height: 70px;
    border-radius: 5px;
    cursor: pointer;
    &:hover {
      border-color: #3c8be3;
    }
    .imgDataUrl {
      width: 70px;
      height: 70px;
    }
  }
</style>
<script>
import myUpload from 'vue-image-crop-upload'
import { crmFileOssSave, getProgressPercent } from '@/api/common'
import {
  // eslint-disable-next-line no-unused-vars
  guid
} from '@/utils'
import axios from 'axios'
export default {
  components: {
    'my-upload': myUpload
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    /** 索引值 用于更新数据 */
    index: Number,
    /** 包含数据源 */
    item: Object,
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      imgDataUrl: '', // the datebase64 url of created image
      isLimit: false,
      fileName: '',
      fileType: '',
      batchId: guid(),
      file: {},
      loading: false
    }
  },
  watch: {
    value: {
      handler(val) {
        this.imgDataUrl = val
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    toggleShow() {
      this.show = !this.show
    },
    /**
       * crop success
       *
       * [param] imgDataUrl
       * [param] field
       */
    cropSuccess(imgDataUrl, field) {
      if (this.isLimit) {
        return
      }
      this.imgDataUrl = imgDataUrl
      var blob = this.dataURLtoBlob(imgDataUrl)
      var file = this.blobToFile(blob, this.fileName)
      const isLt2M = file.size / 1024 / 1024 > 100
      if (isLt2M) {
        this.$message.error('上传文件大小不能超过100M!')
        return false
      }
      var vm = this
      this.loading = true
      crmFileOssSave({
        type: 'img',
        file: file,
        batchId: this.batchId
      }).then(res => {
        vm.getPercent(res.uuid)
      }).catch(res => {
        vm.loading = false
      })
    },
    getPercent(uuid) {
      var vm = this
      setTimeout(function() {
        getProgressPercent({ uuid: uuid }).then((res) => {
          if (res.data != null) {
            if (res.data.hasOwnProperty('url')) {
              vm.file['url'] = res.data.url
            }
          }
          if (res.data.code === 1 && res.data.count === res.data.total) {
            vm.$emit('value-change', {
              index: vm.index,
              batchId: vm.batchId,
              value: vm.file.url
            })
            vm.loading = false
            return vm.file
          }
          if (res.data.code === 0) {
            vm.$message('上传失败！', { type: 'warning' })
            vm.loading = false
            return false
          }
          vm.getPercent(uuid)
        })
      }, 3000)
    },
    // 将base64转换为blob
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    // 将blob转换为file
    blobToFile(theBlob, fileName) {
      return new File([theBlob], fileName, { type: 'img', lastModified: new Date() })
    },
    getFile(fileName, fileType, fileSize) {
      this.isLimit = false
      this.fileName = fileName
      this.fileType = fileType
    },
    /**
       * upload fail
       *
       * [param] status    server api return error status, like 500
       * [param] field
       */
    cropUploadFail(status, field) {
      console.log('-------- upload fail --------')
      console.log(status)
      console.log('field: ' + field)
    }
  }
}
</script>
